#!/usr/bin/env python

#$Id: detframe.py 59 2006-11-27 18:51:56Z magee $
# -------------------------------------------------------------
#
__version__      = '$Revision: 59 $ '[11:-3]
__version_date__ = '$Date: 2006-11-27 18:51:56 +0000 (Mon, 27 Nov 2006) $ '[7:-3]
__author__       = 'R. Bouwens, <bouwens@ucolick.org>, D. Magee, <magee@ucolick.org>'

import pyfits
import multidrizzle
import numarray as N
import os, sys, shutil, glob
from nr_align import wcsclass

class OutFrameRec:
    def __init__(self, rl, rh, dl, dh, pixelscale):
        self.ra = (rl+rh)/2
        self.dec = (dl+dh)/2
        cos = N.cos(self.dec*3.1415926535/180)
        self.scale = pixelscale
        self.orient = 0.0
        self.outnx = int((rh-rl) * 3600 * cos / pixelscale)
        self.outny = int((dh-dl) * 3600 / pixelscale)
        print 'Output Frame = %i x %i' % (self.outnx,self.outny)
        print 'Center = %.4f, %.4f' % (self.ra,self.dec)
        print 'Orientation = %.2f' % (self.orient)
        print 'Pixel Scale = %.3f' % (self.scale)

def determineOutputFrame(db_object, pixelscale):
    db = db_object
    raw_select = 'select filename from raw' 
    db.cur.execute(raw_select)
    raws = [i[0] for i in db.cur.fetchall()]
    filter_select = 'select distinct filter from raw'
    db.cur.execute(filter_select)
    filters = [i[0] for i in db.cur.fetchall()]
    r = []
    d = []
    for filter in filters:
        raw_select = 'select filename from raw where filter = ? AND runflag > 0'
        db.cur.execute(raw_select, (filter,))
        raws = [i[0] for i in db.cur.fetchall()]
        for raw in raws:
            sciImageN = raw.replace('_raw.fits', '_cal4.fits')      
            fin = pyfits.open(sciImageN)
            scihdr = fin['SCI'].header
            dimx = scihdr['NAXIS1']
            dimy = scihdr['NAXIS2']
            wcs = wcsclass.BasicWCS(scihdr)
            r0,d0 = wcs.xy2rd((0,0))
            r1,d1 = wcs.xy2rd((dimx,0))
            r2,d2 = wcs.xy2rd((0,dimy))
            r3,d3 = wcs.xy2rd((dimx,dimy))
            rlist = [r0,r1,r2,r3]
            dlist = [d0,d1,d2,d3]
            r = r + rlist
            d = d + dlist
    rl = min(r)
    rh = max(r)
    dl = min(d)
    dh = max(d)
    outFrame = OutFrameRec(rl, rh, dl, dh, pixelscale)
    return outFrame
